package gui;

import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import Projektarbete.ContactTabListFiller;
import Projektarbete.User;


public class SearchFrame extends JFrame{
	
	private MainFrame mf;
    private String searchWord;
    private ArrayList<User> userList = new ArrayList<User>();
    private ArrayList<User> userList1 = new ArrayList<User>();
    private int listItemIndex = 999;




	public SearchFrame(String nameOrMail, MainFrame mf) {
		this.mf = mf;
		this.searchWord = nameOrMail;
		userList1 = new ContactTabListFiller().searchUser(nameOrMail);
		initComponents();
	}
	
	
	
	private String[][] setList(){
		int index;
		index = userList1.size();
		int i = 0;
		String [][] searchList = new String[index][4];
		Iterator<User> iterator = userList1.iterator();
		while (iterator.hasNext()) {
			User nextUser = iterator.next();
			searchList[i][0] =  nextUser.getUserName();
			searchList[i][1] =  nextUser.getFirstName();
			searchList[i][2] =  nextUser.getLastName();
			searchList[i][3] =  nextUser.getEmail();
			i++;
		}
		return searchList;		
	}
	
	
	
	private boolean alreadyContact(ArrayList<User> list, String name){
		Iterator<User> iterator = list.iterator();
		while (iterator.hasNext()) {
			User nextUser = iterator.next();
			if(nextUser.getUserName().equals(name)){
				return true;
			}
		}
		return false;
		
	}
	
	
	 private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {
		 if(listItemIndex != 999){
			userList = new ContactTabListFiller().getContactList(mf.getUser());
			boolean contact = alreadyContact(userList, userList1.get(listItemIndex).getUserName());
			if (contact != true){
				boolean check = new ContactTabListFiller().addContact(mf.getUser(), userList1.get(listItemIndex).getUserName(), mf);
				System.out.println(check);
			}else{
				JOptionPane.showMessageDialog(jButton1, "The user you chosed is already your contact!");
			}
		}else{
				JOptionPane.showMessageDialog(jButton1, "Please choose a user you wish to add and try again!");
		}
			
	 }
	
	public void disposeWindow(){
    	this.dispose();
    }

	@SuppressWarnings("serial")
	private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            setList(),
            new String [] {
                "Username", "First Name", "Last Name", "Email"
            }
        ) {
            @SuppressWarnings("rawtypes")
			Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            @SuppressWarnings("unchecked")
			public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(2).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(3).setResizable(false);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(100);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1))
        );
        
        
        jButton1.setText("Add");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddButtonActionPerformed(evt);
            }
        });

        MouseListener mouseListener = new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                	if (e.getClickCount() == 1)
                    {
                        Point p = e.getPoint();
                        int row = jTable1.rowAtPoint(p); 
                        listItemIndex = row;
                        System.out.println("index: "  + listItemIndex);
                	}
                } 
            }
        };
        jTable1.addMouseListener(mouseListener);
        
        jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        	public void valueChanged(ListSelectionEvent e) {
        		listItemIndex = jTable1.getSelectedRow();
                System.out.println("index: "  + listItemIndex);
        	}
        });

       

        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter(){
        	public void windowClosing(WindowEvent e){
        		disposeWindow();
        	}
        });

        pack();
    }// </editor-fold>


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

       
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration
}


